import {Meteor} from 'meteor/meteor'
import {HTTP} from 'meteor/http';
// import {UserList} from '/imports/collections/collection'

// 用来生成token
import jwt from 'jsonwebtoken'
// 生成token
var content ={msg:"today  is  a  good  day"}; // 要生成token的主题信息
var secretOrPrivateKey="I am a goog man!" // 这是加密的key（密钥） 
var token = jwt.sign(content, secretOrPrivateKey, {
  expiresIn: 60*60*24  // 24小时过期
})

  Meteor.methods({
    test:function(data){
      
    },
    // 密码重置
    resetPW:function(userID){
      // Accounts.setPassword(user_id,'123456')
      var user=Meteor.users.findOne({_id:userID})
      // 密码重置
      Meteor.users.update({_id:userID},{$set:{'mypassword':'123456'}});
      return user;
    },
    // 版本选择
    // selectVersion:function(user){
    //   Meteor.users.update({_id:user._id},{$set:{'version':user.mg_state}});
    // }
  })



  HTTP.methods({

    '/register':function(data){
      var status={};
      // console.log('data-3000qqq:',data,this.request.headers);
      this.setContentType('application/json');
      this.addHeader('Access-Control-Allow-Origin', '*');
      this.unblock;
      // 验证
      var findUser = Meteor.users.findOne({ username : data.username })
      if (findUser) {
        // console.log('find user :' + data.username)
        // console.log(findUser)
        status={
          code: 200,
          error:1,
          msg:'注册失败，用户名被占用',
          data:''
          }
      }else{
        status={
          code: 200,
          error:0,
          msg:'注册成功',
          data:''
        }
        // 创建新用户
        // Accounts.createUser(data);
        Meteor.users.insert({
          "username":data.username,
          "mypassword":data.password,
          "isLogin":false,
          "mg_state":false           //默认使用lite版本
        })
        // 允许删除、更新用户数据
        Meteor.users.allow({ remove: () => true });
        Meteor.users.allow({ update: () => true });
        Meteor.users.allow({ insert: () => true });
      }
      return status
    },
    '/login':function(data){
      var status={};
      console.log("打印出token000："+token)
      // console.log('login-3000uuu:',data);

      this.setContentType('application/json');
      this.addHeader('Access-Control-Allow-Origin', '*');
      this.unblock;

      var findUsername = Meteor.users.findOne({ username : data.username })
      var istrue=false;
      if(findUsername.mypassword===data.password){
        istrue=true
      }
      
      // console.log(findUsername.services.password.bcrypt);
      // console.log(findUsername.mypassword+"用户密码")
      var findUserId=Meteor.users.findOne({_id:data.userId})

      // 对token进行校验
      var checkToken=true;
      jwt.verify(data.token, secretOrPrivateKey, function (err, decode) {
        if (err) {  //  时间失效的时候/ 伪造的token          
          console.log(data+"校验失败77")
          status={
            code: 200,
            error:1,
            msg:'token无效',
            data:''
          }
        } else {
            // rq.decode = decode; 
            // console.log(decode.msg);   // today  is  a  good  day
            // next();
            console.log("打印出decode："+JSON.stringify(decode))
            console.log(data+"校验成功00")
            status={
              code: 200,
              error:0,
              msg:'token有效',
              data:{
                userId:findUsername._id,
                username:findUsername.username,
                mg_state:findUsername.mg_state,
                token:token
              }
            }
            checkToken=false;
        }
    })

    
      if (checkToken&&istrue) {
        data.isLogin=true;
          status={
            code: 200,
            error:0,
            msg:'登录成功',
            data:{
              userId:findUsername._id,
              username:findUsername.username,
              mg_state:findUsername.mg_state,
              token:token
            },
            }
          console.log(JSON.stringify(findUsername)+"====用户名密码登录成功")
          // this.setUserId(findUserpw._id)
      // console.log("登录成功："+JSON.stringify(status))
      }else if(checkToken){
        console.log(data+"失败00")
        status={
          code: 200,
          error:1,
          msg:'登录失败，用户名或密码错误!',
          data:''
        }
      }



      // if(findUserId._id){
      //   data.isLogin=true;
      //     status={
      //       code: 200,
      //       error:0,
      //       msg:'登录成功',
      //       data:{
      //         userId:findUserId._id,
      //         username:findUserId.username
      //       },
      //       }
      //     console.log(JSON.stringify(findUserId)+"====ID登录成功")
      // }else{
      //   console.log(findUserId._id+"ID登录失败")
      //   status={
      //     code: 200,
      //     error:1,
      //     msg:'登录失败，用户ID不存在!',
      //     data:''
      //   }
      // }

      return status
    },

    '/logout':function(data){
      var status={};
      var findUserId=Meteor.users.findOne({_id:data.userId})
      if(findUserId){
        data.isLogin=false;
        status={
          code: 200,
          error:0,
          msg:'退出成功!',
          data:{
          userId:findUserId._id,
          username:findUserId.username
          },
        }
        console.log("退出成功"+findUserId.username)
      }else{
        status={
          code: 200,
          error:1,
          msg:'退出失败!',
          data:{
          userId:findUserId._id,
          username:findUserId.username
          },
        }
      }
      return status;
    }
  });